package com.caiheng.api.service.product.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.mer.MerMapper;
import com.caiheng.api.dao.platform.PlatformSplitMapper;
import com.caiheng.api.dao.product.*;
import com.caiheng.api.entity.mer.Mer;
import com.caiheng.api.entity.platform.PlatformSplit;
import com.caiheng.api.entity.product.*;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.product.ProductOrderInfoService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductOrderInfoServiceImpl extends BaseServiceImpl<ProductOrderInfoMapper, ProductOrderInfo> implements ProductOrderInfoService {
    @Resource
    private ProductOrderInfoMapper productOrderInfoMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductAttrValueMapper productAttrValueMapper;
    @Resource
    private ProductOrderMapper productOrderMapper;
    @Resource
    private MerMapper merMapper;

    @Resource
    private ProductAttrValueMapper attrValueMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    @Resource
    private PlatformSplitMapper platformSplitMapper;


    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址
    @Value("${web.uploadPath}")
    private String uploadPath;

    @Override
    public ProductOrderInfo selectOneByOrderId(Long order_id) {
        QueryWrapper<ProductOrderInfo> qwInfos = new QueryWrapper<>();
        qwInfos.eq("order_id", order_id);
        qwInfos.eq("state",1);
        qwInfos.eq("is_del", 0);
        qwInfos.last("limit 1");
        return productOrderInfoMapper.selectOne(qwInfos);
    }

    @Override
    public List<ProductOrderInfo> selectListByOrderId(Mer mer,Long order_id) {

        QueryWrapper<ProductOrderInfo> qwInfos = new QueryWrapper<>();
        qwInfos.eq("order_id", order_id);
//        qwInfos.eq("state",1);
        qwInfos.eq("is_del", 0);
        List<ProductOrderInfo> infos = productOrderInfoMapper.selectList(qwInfos);
        if(infos != null && infos.size() > 0) {
            for (ProductOrderInfo orderInfo : infos) {
                if(StrUtil.isEmpty(orderInfo.getSkuName())) {
                    ProductAttrValue attrValue = productAttrValueMapper.selectById(orderInfo.getSkuId());
                    if (attrValue != null) {
                        orderInfo.setSkuName(attrValue.getSku());
                    }
                }

                Product product = productMapper.selectById(orderInfo.getProductId());
                if (product != null) {
                    orderInfo.setProductName(product.getStoreName());
                    orderInfo.setImgUrl(imgPrefix + product.getImage());
                }

                if(mer.getShopType() != 8) {

                    Date expireTime = orderInfo.getCodeExpireTime();
                    //不存在未生成的情况下，新生成，或者是 已经过期的二维码 超过1分钟的
                    //返回值为：{天, 时, 分, 秒}
                    //60秒之后的时间
                    Date date = null;
                    if (expireTime != null) {
                        date = DateUtil.getAfterSecondsByOld(expireTime, 60);
                    } else {
                        date = DateUtil.getAfterSecondsByOld(new Date(), 60);
                    }

                    if (expireTime == null || (expireTime != null && new Date().getTime() > date.getTime())) {
                        try {
                            String qrcode = "";
                            String fileName = "order_info_qr_" + orderInfo.getId() + ".jpg";
                            String content = "{\"qrtype\":\"orderInfo\",\"id\":" + orderInfo.getId() + ",\"expire_time\":" + date.getTime() + "}";
                            Aes aes = new Aes();
                            int upload_type = OssUtil.TYPE_ORDER_INFO_VERIFYCODE_IMGS;
                            content = aes.encrypt(content);
                            System.out.println("content:  " + content);
                            String img_key = "";
                            img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                            QRCodeUtilEx.createQrCodeImg(content, "核销码：" + orderInfo.getVerifyCode(),
                                    null, uploadPath + img_key, true, fileName, upload_type);
                            qrcode = img_key;
                            orderInfo.setQrCode(qrcode);
                            orderInfo.setCodeExpireTime(new Date());
                            productOrderInfoMapper.updateById(orderInfo);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        }
        return infos;
    }

    @Override
    public ProductOrderInfo getInfoQrCode(Long info_id,int reset_qr_code) {
        ProductOrderInfo orderInfo = productOrderInfoMapper.selectById(info_id);
        if(orderInfo!=null && reset_qr_code == 1){
            Date expireTime = orderInfo.getCodeExpireTime();
            //不存在未生成的情况下，新生成，或者是 已经过期的二维码 超过1分钟的
            //返回值为：{天, 时, 分, 秒}
            //60秒之后的时间
            Date date = null;
            if(expireTime != null){
                date = DateUtil.getAfterSecondsByOld(expireTime,60);
            }else{
                date = DateUtil.getAfterSecondsByOld(new Date(),60);
            }
            if(expireTime == null || (expireTime != null && new Date().getTime() > date.getTime() )){
                try{
                    String qrcode = "";
                    String fileName = "order_info_qr_" + orderInfo.getId() + ".jpg";
                    String content = "{\"qrtype\":\"orderInfo\",\"id\":"+orderInfo.getId()+",\"expire_time\":"+date.getTime()+"}";
                    Aes aes = new Aes();
                    int upload_type = OssUtil.TYPE_ORDER_INFO_VERIFYCODE_IMGS;
                    content = aes.encrypt(content);
                    System.out.println("content:  "+ content);
                    String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, "核销码：" + orderInfo.getVerifyCode(),
                            null, uploadPath + img_key, true,fileName,upload_type);
                    qrcode = img_key;
                    orderInfo.setQrCode(qrcode);
                    orderInfo.setCodeExpireTime(new Date());
                    productOrderInfoMapper.updateById(orderInfo);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
        return orderInfo;
    }

    @Override
    @Transactional
    public int deleteInfo(Long infoId) {
        int ret = 0;
        try{
            ProductOrderInfo orderInfo = productOrderInfoMapper.selectById(infoId);
            if(orderInfo != null){
                QueryWrapper<ProductOrderInfo> qw = new QueryWrapper<>();
                qw.select("id");
                qw.eq("order_id",orderInfo.getOrderId());
                long infoCount =productOrderInfoMapper.selectCount(qw);
                if(infoCount == 1){
                    return -2;
                }
                ret = productOrderInfoMapper.deleteById(orderInfo.getId());
                if(ret <= 0){
                    throw new TransactionalException("userMapper updateById error");
                }
            }

            ProductOrder order = productOrderMapper.selectById(orderInfo.getOrderId());
            if(order != null){

                if(order.getStatus() >= 2)
                {
                    return -1;
                }
                Mer mer = merMapper.selectById(order.getMerId());
                double d1Total = 0,d2Total = 0,d3Total = 0,dTotalFee = 0,dTotalSettlement = 0,totalMoney = 0;

                QueryWrapper<ProductOrderInfo> qw = new QueryWrapper<>();
                qw.eq("order_id",order.getId());
                qw.eq("is_del",0);
                List<ProductOrderInfo> orderInfos = productOrderInfoMapper.selectList(qw);
                if(CollUtil.isNotEmpty(orderInfos)){
                    for (ProductOrderInfo orderInfo1 : orderInfos){

                        ProductAttrValue attrValue = attrValueMapper.selectById(orderInfo1.getSkuId());
                        int count = orderInfo1.getCount();
                        totalMoney += count * orderInfo1.getSinglePrice().doubleValue();
                        Product product = productMapper.selectById(orderInfo1.getProductId());
                        for (int i = 0; i < count; i++){
                            if(product.getIsSub() == 1){
                                double totalSplitMoney = 0;
                                if(product.getIsCoupon() == 0){
                                    // 按照售价比例
                                    totalSplitMoney = mer.getSubRate().doubleValue() * orderInfo.getSinglePrice().doubleValue() / 100;
                                    //计算当前商品的分润以及手续费
                                    if(mer.getSubType() == 0){//按照固定金额
                                        double fee = mer.getSubRate().doubleValue() * orderInfo.getCount();
                                        orderInfo.setMerFee(new BigDecimal(fee));//商家手续费（分佣）
                                        dTotalFee += fee;
                                        double settlement = orderInfo.getSinglePrice().doubleValue() - fee;
                                        orderInfo.setMerSettlement(new BigDecimal(settlement));//清算金额
                                        dTotalSettlement += settlement;
                                    } else if(mer.getSubType() == 1){//按照比例
                                        //手续费  176 * 10% *
                                        double fee = orderInfo.getSinglePrice().doubleValue() *  mer.getSubRate().doubleValue() / 100;
                                        orderInfo.setMerFee(new BigDecimal(fee));//商家手续费（分佣）
                                        dTotalFee += fee;
                                        //结算金额
                                        double settlement = orderInfo.getSinglePrice().doubleValue() - fee;
                                        orderInfo.setMerSettlement(new BigDecimal(settlement));
                                        dTotalSettlement += settlement;
                                    }
                                }else{
                                    // 按照售价比例
                                    totalSplitMoney = mer.getSubCouponRate().doubleValue() * orderInfo.getSinglePrice().doubleValue() / 100;
                                    //计算当前商品的分润以及手续费
                                    //手续费
                                    double fee = orderInfo.getSinglePrice().doubleValue() *  mer.getSubCouponRate().doubleValue() / 100;
                                    orderInfo.setMerFee(new BigDecimal(fee));//商家手续费（分佣）
                                    dTotalFee += fee;
                                    //结算金额
                                    double settlement = orderInfo.getSinglePrice().doubleValue() - fee;
                                    orderInfo.setMerSettlement(new BigDecimal(settlement));
                                    dTotalSettlement += settlement;
                                }
                                orderInfo.setSplitMoney(new BigDecimal(totalSplitMoney));

                                orderInfo.setMerId(product.getMerId());

                                QueryWrapper<PlatformSplit> qwSplit = new QueryWrapper<>();
                                qwSplit.eq("split_type","proportion");//按照比例分成
                                qwSplit.last("limit 1");
                                PlatformSplit platformSplit = platformSplitMapper.selectOne(qwSplit);
                                if(platformSplit != null){
                                    //需要分成的总金额
                                    // 有两种分成方式 按照固定金额   按照售价比例
                                    double splitMoney = 0;
                                    if(mer.getSubType() == 0){//按照固定金额
                                        splitMoney = mer.getSubRate().doubleValue();
                                    }else if(mer.getSubType() == 1){
                                        if(product.getIsCoupon() == 0){
                                            // 按照售价比例
                                            splitMoney = attrValue.getPrice().doubleValue() * mer.getSubRate().doubleValue() / 100;
                                        }else{
                                            // 按照售价比例
                                            splitMoney = attrValue.getPrice().doubleValue() * mer.getSubCouponRate().doubleValue() / 100;
                                        }
                                    }
                                    if(platformSplit.getSplitType().equals("jine")){//按照金额来分
                                        //平台
                                        orderInfo.setPlatformRate(platformSplit.getPlatformSplit());
                                        double dd1 = platformSplit.getPlatformSplit().doubleValue() * count;
                                        orderInfo.setPlatformSplit(new BigDecimal(dd1));
                                        d1Total += platformSplit.getPlatformSplit().doubleValue() * count;
                                        //业主
                                        orderInfo.setProprietorRate(platformSplit.getProprietorSplit());
                                        double dd2 = platformSplit.getProprietorSplit().doubleValue() * count;
                                        orderInfo.setProprietorSplit(new BigDecimal(dd2));
                                        d2Total += platformSplit.getProprietorSplit().doubleValue() * count;
                                        //物业公司
                                        orderInfo.setPropertyRate(platformSplit.getPropertySplit());
                                        double dd3 = platformSplit.getPropertySplit().doubleValue() * count;
                                        orderInfo.setPropertySplit(new BigDecimal(dd3));
                                        d3Total += platformSplit.getPropertySplit().doubleValue() * count;
                                    }else if(platformSplit.getSplitType().equals("proportion")) {//按照百分比来分
                                        //平台
                                        double d1 = splitMoney * platformSplit.getPlatformSplit().doubleValue() / 100;
                                        orderInfo.setPlatformRate(platformSplit.getPlatformSplit());
                                        orderInfo.setPlatformSplit(new BigDecimal(d1 * count));
                                        d1Total += d1 * count;
                                        //业主
                                        double d2 = splitMoney * platformSplit.getProprietorSplit().doubleValue() / 100;
                                        orderInfo.setProprietorRate(platformSplit.getProprietorSplit());
                                        orderInfo.setProprietorSplit(new BigDecimal(d2 * count));
                                        d2Total += d2 * count;
                                        //物业公司
                                        double d3 = splitMoney * platformSplit.getPropertySplit().doubleValue() / 100;
                                        orderInfo.setPropertyRate(platformSplit.getPropertySplit());
                                        orderInfo.setPropertySplit(new BigDecimal(d3 * count));
                                        d3Total += d3 * count;
                                    }
                                }
                            }
                        }
                    }
                }

                order.setTotalPrice(new BigDecimal(totalMoney));
                order.setTotalPayMoney(new BigDecimal(totalMoney));
                order.setPayPrice(new BigDecimal(totalMoney));
                order.setPlatformSplit(new BigDecimal(d1Total));
                order.setProprietorSplit(new BigDecimal(d2Total));
                order.setPropertySplit(new BigDecimal(d3Total));

                //商家手续费和结算金额计算
                if(mer != null){
                    order.setMerSubType(mer.getSubType());
                    order.setMerFee(new BigDecimal(dTotalFee));
                    order.setMerSettlement(new BigDecimal(dTotalSettlement));
                }
                ret = productOrderMapper.updateById(order);
                if(ret <= 0){
                    throw new TransactionalException("userMapper updateById error");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("deleteInfo system error");
        }
        return ret;
    }

    @Override
    @Transactional
    public Map<String,Object> addInfo(User user, ProductOrder order, Product product, ProductAttrValue attrValue, int count) {
        int ret= 0 ;
        Map<String,Object> map = new HashMap<>();
        try{
            QueryWrapper<ProductOrderInfo> qw = new QueryWrapper<>();
            qw.eq("is_del",0);
            qw.eq("is_pay",0);
            qw.eq("product_id",product.getId());
            qw.eq("sku_id",attrValue.getId());
            qw.last("limit  1");
            ProductOrderInfo orderInfo = productOrderInfoMapper.selectOne(qw);
            if(orderInfo == null){
                orderInfo = new ProductOrderInfo();
                orderInfo.setIsFc(0);
                orderInfo.setMerId(order.getMerId());
                orderInfo.setVerifyCode(OrderUtil.getVerfiyNoAndRandom());//核销码
                orderInfo.setVerifyCount(0);
                orderInfo.setIsVerify(0);
                orderInfo.setSettlementState(0);
                orderInfo.setCount(count);
                orderInfo.setSinglePrice(attrValue.getPrice());
                orderInfo.setIsDel(0);
                if(user.getPropertyId()!=null){
                    orderInfo.setPropertyId(user.getPropertyId());
                }
                if(user.getEstateId()!=null){
                    orderInfo.setEstateId(user.getEstateId());
                }

                orderInfo.setProductId(attrValue.getProductId());
                orderInfo.setOrderId(order.getId());
                orderInfo.setSinglePrice(new BigDecimal(attrValue.getPrice().doubleValue()));
                orderInfo.setTotalMoney(new BigDecimal(MathUtil.getDoubleUp(attrValue.getPrice().doubleValue() * count)));
                orderInfo.setState(1);
                orderInfo.setCreateTime(new Date());
                orderInfo.setSkuId(attrValue.getId());
                //原价
                orderInfo.setOriginPrice(attrValue.getOtPrice());
                orderInfo.setSettlementState(0);

                ret = productOrderInfoMapper.insert(orderInfo);
                if(ret <= 0){
                    throw new TransactionalException("productOrderInfoMapper insert error");
                }
            }else{
                int infoCount = orderInfo.getCount();
                int totalCount = infoCount + count;
                orderInfo.setCount(totalCount);
                orderInfo.setTotalMoney(new BigDecimal(MathUtil.getDoubleUp(attrValue.getPrice().doubleValue() * totalCount)));

                ret = productOrderInfoMapper.updateById(orderInfo);
                if(ret <= 0){
                    throw new TransactionalException("productOrderInfoMapper updateById error");
                }
            }

            double totalPrice = 0;
            QueryWrapper<ProductOrderInfo> qwInfos = new QueryWrapper<>();
            qwInfos.eq("order_id", order.getId());
            qwInfos.eq("state",1);
            qwInfos.eq("is_del",0);
            List<ProductOrderInfo> orderInfos = productOrderInfoMapper.selectList(qwInfos);
            if(CollUtil.isNotEmpty(orderInfos)){
                for (ProductOrderInfo info : orderInfos){
                    totalPrice += info.getTotalMoney().doubleValue();


                    if(StrUtil.isEmpty(info.getSkuName())) {
                        attrValue = productAttrValueMapper.selectById(info.getSkuId());
                        if (attrValue != null) {
                            info.setSkuName(attrValue.getSku());
                        }
                    }


                    product = productMapper.selectById(orderInfo.getProductId());
                    if (product != null) {
                        info.setProductName(product.getStoreName());
                        info.setImgUrl(imgPrefix + product.getImage());
                    }
                }
                order.setTotalPrice(new BigDecimal(totalPrice));
                order.setPayPrice(new BigDecimal(totalPrice));
                ret = productOrderMapper.updateById(order);
                if(ret <= 0){
                    throw new TransactionalException("productOrderMapper updateById error");
                }
            }
            order.setInfos(orderInfos);
            map.put("order",order);
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("ret",ret);
        return map;
    }

    @Override
    public Map<String,Object> updateInfo(ProductOrder order, ProductOrderInfo orderInfo, int count) {
        Map<String, Object> map = new HashMap<>();
        int ret= 0;
        try{
            orderInfo.setCount(count);
            if(count == 0){
                orderInfo.setIsDel(1);
            }else{
                orderInfo.setIsDel(0);
            }
            orderInfo.setTotalMoney(new BigDecimal(MathUtil.getDoubleUp(orderInfo.getSinglePrice().doubleValue() * count)));
            ret = productOrderInfoMapper.updateById(orderInfo);
            if(ret <= 0){
                throw new TransactionalException("productOrderInfoMapper updateById error");
            }

            double totalPrice = 0;
            QueryWrapper<ProductOrderInfo> qwInfos = new QueryWrapper<>();
            qwInfos.eq("order_id", order.getId());
            qwInfos.eq("is_del",0);
            List<ProductOrderInfo> orderInfos = productOrderInfoMapper.selectList(qwInfos);
            if(CollUtil.isNotEmpty(orderInfos)){
                for (ProductOrderInfo info : orderInfos){
                    totalPrice += info.getTotalMoney().doubleValue();

                    if(StrUtil.isEmpty(info.getSkuName())) {
                        ProductAttrValue attrValue = productAttrValueMapper.selectById(info.getSkuId());
                        if (attrValue != null) {
                            info.setSkuName(attrValue.getSku());
                        }
                    }

                    Product product = productMapper.selectById(info.getProductId());
                    if (product != null) {
                        info.setProductName(product.getStoreName());
                        info.setImgUrl(imgPrefix + product.getImage());
                    }

                }
                order.setTotalPrice(new BigDecimal(totalPrice));
                order.setPayPrice(new BigDecimal(totalPrice));
                ret = productOrderMapper.updateById(order);
                if(ret <= 0){
                    throw new TransactionalException("productOrderMapper updateById error");
                }
            }
            map.put("allPrice",MathUtil.getDoubleUp(totalPrice));
            map.put("payPriceFen",MathUtil.getDoubleUp(totalPrice* 100) );
            order.setInfos(orderInfos);
            map.put("order",order);
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("ret",ret);
        return map;
    }
}
